import { defineStore } from 'pinia'
import store from '../index'
import type { DictDataVO } from '@/api/system/dict/dict.data'
import { getSimpleDictDataList } from '@/api/system/dict/dict.data'

export interface DictValueType {
  value: any
  label: string
  colorType?: string // 修正拼写错误 clorType → colorType
  cssClass?: string
}

export interface DictState {
  dictMap: Record<string, DictValueType[]> // 使用普通对象替代 Map
  isSetDict: boolean
}

export const useDictStore = defineStore('dict', {
  state: (): DictState => ({
    dictMap: {},
    isSetDict: false
  }),

  getters: {
    getDictMap(): Record<string, DictValueType[]> {
      try {
        const cache = uni.getStorageSync('dict')
        if (cache) {
          this.dictMap = JSON.parse(cache) // 反序列化
        }
        return this.dictMap
      } catch (e) {
        console.error('字典解析失败', e)
        return {}
      }
    },
    getIsSetDict(): boolean {
      return this.isSetDict
    }
  },

  actions: {
    async setDictMap() {
      try {
        const cache = uni.getStorageSync('dict')
        if (cache) {
          this.dictMap = JSON.parse(cache)
          this.isSetDict = true
          return
        }
      } catch (e) {
        console.warn('本地字典缓存异常', e)
      }

      await this.fetchAndSetDict()
    },

    async fetchAndSetDict() {
      try {
        const res = await getSimpleDictDataList()
        const dictDataMap: Record<string, DictValueType[]> = {}

        res.forEach((dictData: DictDataVO) => {
          const dictType = dictData.dictType
          if (!dictDataMap[dictType]) {
            dictDataMap[dictType] = []
          }
          
          dictDataMap[dictType].push({
            value: dictData.value,
            label: dictData.label,
            colorType: dictData.colorType,
            cssClass: dictData.cssClass
          })
        })

        this.dictMap = dictDataMap
        this.isSetDict = true
        uni.setStorageSync('dict', JSON.stringify(dictDataMap)) // 序列化存储
      } catch (error) {
        console.error('获取字典失败', error)
        throw error
      }
    },

    getDictByType(type: string): DictValueType[] {
      if (!this.isSetDict) {
        this.setDictMap()
      }
      return this.dictMap[type] || []
    },

    async resetDict() {
      try {
        uni.removeStorageSync('dict')
        await this.fetchAndSetDict()
      } catch (e) {
        console.error('重置字典失败', e)
      }
    }
  },
  // 添加持久化配置
  persist: {
  	key: 'dict-storage', // 指定一个存储的key
  	storage: {
  		getItem(key) {
  			return uni.getStorageSync(key)
  		},
  		setItem(key, value) {
  			return uni.setStorageSync(key, value)
  		}
  	}
  }
})

export const useDictStoreWithOut = () => {
  return useDictStore(store)
}